package com.suse.service.user.controller;

import cn.hutool.core.util.ObjectUtil;
import com.suse.common.config.response.ApiException;
import com.suse.common.config.response.R;
import com.suse.common.util.jwt.JwtUtil;
import com.suse.model.dto.UserDto;
import com.suse.service.user.entity.User;
import com.suse.service.user.model.param.LoginParam;
import com.suse.service.user.model.param.RegisterParam;
import com.suse.service.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import static com.suse.common.config.response.SimpleCode.LOGOUT_SUCCESS;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-18
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/dev-api/user")
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public R login(@Valid @RequestBody LoginParam loginParam) {
        return userService.login(loginParam);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public R getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        User user = JwtUtil.parseToken(token, User.class);
        if (ObjectUtil.isNull(user)) {
            throw new ApiException("无效的令牌！");
        }
        return R.put("userInfo",user).success();
    }

    @ApiOperation(value = "用户注销")
    @PostMapping("/logout")
    public R logout() {
        return R.success(LOGOUT_SUCCESS);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public R register(@Valid @RequestBody RegisterParam registerParam) {
        return userService.register(registerParam);
    }

    @GetMapping("/inner/dto/{id}")
    public UserDto getUserDtoById(@PathVariable("id") String id) {
        return userService.getUserDtoById(id);
    }

}

